package com.xtjc.recsyslog.netty.entity;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import com.xtjc.recsyslog.util.ConverUtil;
import io.netty.channel.Channel;
import lombok.Data;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

@Data

public class ChargeEntity {

    //唯一标识
    private String[] sn16;

    private String snBCD;

    //通道
    private Channel channel;

    //发送序列号
    private String[] serialNumber;

    private AtomicInteger counter = new AtomicInteger(1);

    private AtomicInteger sequenceNumber = new AtomicInteger(1);


    public ChargeEntity(String[] sn16, Channel channel) {
        this.sn16 = sn16;
//        this.snBCD = BCD.bcdToStr(ConverUtil.hexArrayToByteArray(sn16));
        this.snBCD = String.join("", sn16);
        this.channel = channel;
        this.serialNumber = new String[]{"00", "00"};
    }

    public static void main(String[] args) {
        String[] sn16 = {"22", "00", "00", "00", "00", "00", "01"};
        ChargeEntity a = new ChargeEntity(sn16, null);
        for (int i = 0; i < 100; i++) {
            String[] serialNumber1 = a.getSerialNumber();
            System.out.println(ArrayUtil.toString(serialNumber1));
        }
    }

    public String[] getSerialNumber() {
        return getNum(counter);
    }

    //32 01 02 00 00 00 00  SN  11 抢号 15 11 16 15 55 35 02 60
    public String[] getTxnSeqNum() {
        String[] res = new String[16];
        System.arraycopy(sn16, 0, res, 0, sn16.length);
        res[7] = "01";
        String[] times = getTimes();
        System.arraycopy(times, 0, res, 8, times.length);
        String[] num = getNum(sequenceNumber);
        System.arraycopy(num, 0, res, 14, num.length);
        return res;
    }

    private String[] getNum(AtomicInteger num) {
        int i = num.getAndIncrement();
        if (i == 65534) {
            num.set(1);
        }
        String s1 = ConverUtil.byteToHex(i);
        if (s1.length() == 2) {
            return new String[]{"00", s1};
        } else {
            return ConverUtil.convertHexStringToStringArray(s1);
        }
    }

    private String[] getTimes() {
        Date date = DateUtil.date();
        String res = DateUtil.format(date, "yy-MM-dd-HH-mm-ss");
        return res.split("-");
    }


}
